﻿package com.hotel.front;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Util;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.google.gson.Gson;
import com.hotel.BL.GenericLogic;
import com.hotel.BL.LoginLogic;
import com.hotel.BL.ReservationLogic;
import com.hotel.BL.TaskLogic;

import data.General;
import data.Task;
import data.User;
import data.passingData.ResultData;

@SuppressWarnings("serial")
public class TaskService extends HttpServlet {	
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm",Locale.ENGLISH);
	//http://localhost:8080/taskService?func=CountTask
	//http://localhost:8080/taskService?func=GetTaskList
	//http://localhost:8080/taskService?func=CloseTask&taskId=46
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String func = req.getParameter("func");
		try{
			if(func.equals("GetTaskListAll"))
				GetTaskListAll(req,resp);
			else if(func.equals("CloseTask"))
				CloseTask(req,resp);
			else if(func.equals("AddTaskNote"))
				AddTaskNote(req,resp);
			else if(func.equals("AddTaskNoteFont"))
				AddTaskNoteFont(req,resp);
			else if(func.equals("AddTaskNoteGroup"))
				AddTaskNoteGroup(req,resp);
			else if(func.equals("GetTaskNoteList"))
				GetTaskNoteList(req,resp);
			else if (func.equals("editTitle")) 
				EditTitleTaskNote(req, resp);
			else if (func.equals("editDetail")) 
				EditDetailTaskNote(req, resp);
			else if (func.equals("editDue")) 
				EditDueTaskNote(req, resp);
			else if (func.equals("editStar")) 
				EditIsStar(req, resp);
			else if (func.equals("editTrash")) 
				editTrash(req, resp);
			else if (func.equals("editClose")) 
				EditClose(req, resp);
			else if (func.equals("GetFrontTask"))
				GetFrontTask(req, resp);
			else if (func.equals("GetFrontTaskAll"))
				GetFrontTaskAll(req, resp);
			else if (func.equals("UpdateLastStay"))
				UpdateLastStay(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void GetTaskListAll(HttpServletRequest req, HttpServletResponse resp) throws IOException, ParseException
	{
		HttpSession session=req.getSession(true);
		long hotelId = 1;
		if(session.getAttribute("hotelId") != null)
			hotelId = (Long)session.getAttribute("hotelId");
		
		List<Task> task = new TaskLogic(req,resp).GetFistAllTask(hotelId);
		
		Gson gson = new Gson();
		
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(task));
	}
	private void CloseTask(HttpServletRequest req, HttpServletResponse resp) throws JSONException, IOException
	{		
		String taskId = req.getParameter("taskId");
		JSONObject obj = new JSONObject();
		
		Boolean rs = false;
		
		try{
			long id = Long.parseLong(taskId);
			rs = new TaskLogic(req,resp).CloseTask(id);
		}
		catch(NumberFormatException e){}
		
		obj.put("Result", rs);
		
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void AddTaskNoteFont(HttpServletRequest req, HttpServletResponse resp) throws JSONException, IOException, EntityNotFoundException, ParseException 
	{
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
		hotelId = (Long) session.getAttribute("hotelId");
		String Detail = req.getParameter("detail");
		Date date = formatter.parse(req.getParameter("due"));
		boolean IsStar = Boolean.parseBoolean(req.getParameter("isStar"));
		String roomName = req.getParameter("roomName");
		String Status = req.getParameter("status");
		String TaskTitle = req.getParameter("taskTitle");
		Task obj;
		if(req.getParameter("due").equals("0000-00-00 00:00:00"))
			obj = new TaskLogic(req,resp).AddTaskNote(Detail,hotelId,IsStar,Status,TaskTitle,roomName);
		else
			obj = new TaskLogic(req,resp).AddTaskNote(Detail,hotelId,IsStar,Status,TaskTitle,roomName,date);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	private void AddTaskNote(HttpServletRequest req, HttpServletResponse resp) throws JSONException, IOException, EntityNotFoundException, ParseException 
	{
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
		hotelId = (Long) session.getAttribute("hotelId");
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String Detail = req.getParameter("detail");
		Date date = formatter.parse(req.getParameter("due"));
		boolean IsStar = Boolean.parseBoolean(req.getParameter("isStar"));
		String Status = req.getParameter("status");
		String TaskTitle = req.getParameter("taskTitle");
		String roomName = req.getParameter("roomName");
		Long res_id =Long.parseLong(req.getParameter("res_id"));
		Task obj;
		if(req.getParameter("due").equals("0000-00-00 00:00:00"))
			obj = new TaskLogic(req,resp).AddTaskNote(Detail,hotelId,IsStar,Status,TaskTitle,roomName);
		else
			obj = new TaskLogic(req,resp).AddTaskNote(Detail,hotelId,IsStar,Status,TaskTitle,roomName,date);
		
		String task_id = String.valueOf(obj.getId());
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		resLogic.EditTaskList(hotelId, res_id, task_id);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	private void AddTaskNoteGroup(HttpServletRequest req, HttpServletResponse resp) throws JSONException, IOException, EntityNotFoundException, ParseException 
	{
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		Gson gson = new Gson();
		if (session.getAttribute("hotelId") != null)
		hotelId = (Long) session.getAttribute("hotelId");
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String Detail = req.getParameter("detail");
		boolean IsStar = Boolean.parseBoolean(req.getParameter("isStar"));
		String roomName = req.getParameter("roomName");
		String Status = req.getParameter("status");
		String TaskTitle = req.getParameter("taskTitle");
		Long group_id =Long.parseLong(req.getParameter("group_id"));
		Date date = formatter.parse(req.getParameter("due"));
		Task obj;
		if(req.getParameter("due").equals("0000-00-00 00:00:00"))
			obj = new TaskLogic(req,resp).AddTaskNote(Detail,hotelId,IsStar,Status,TaskTitle,roomName);
		else
			obj = new TaskLogic(req,resp).AddTaskNote(Detail,hotelId,IsStar,Status,TaskTitle,roomName,date);
		String task_id = String.valueOf(obj.getId());
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		resLogic.EditTaskListGroup(hotelId, group_id, task_id);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	private void EditIsStar(HttpServletRequest req, HttpServletResponse resp) throws ParseException, IOException, EntityNotFoundException 
	{
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		Boolean isStar =Boolean.valueOf(req.getParameter("status_star"));
		if(isStar==false){
			isStar = true;
		}else{
			isStar = false;
		}
		Long id_int = Long.parseLong(req.getParameter("id_int"));
		TaskLogic tLogic = new TaskLogic(req,resp);
		Task isStarEdit = tLogic.EditIsStarTask(hotelId, id_int, isStar);
		resp.setContentType("text/plain; charset=UTF-8");
		if (isStarEdit != null) {
			resp.getWriter().println(gson.toJson(isStarEdit));
		} else {
			resp.getWriter().println(gson.toJson(false));
		}
	}
	private void EditTitleTaskNote(HttpServletRequest req, HttpServletResponse resp) throws ParseException, IOException, EntityNotFoundException 
	{
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String title = req.getParameter("title");
		Long id_int = Long.parseLong(req.getParameter("id_int"));
		TaskLogic tLogic = new TaskLogic(req,resp);
		Task titleEdit = tLogic.EditTitleTask(hotelId, id_int, title);
		resp.setContentType("text/plain; charset=UTF-8");
		if (titleEdit != null) {
			resp.getWriter().println(gson.toJson(titleEdit));
		} else {
			resp.getWriter().println(gson.toJson(false));
		}
	}
	private void EditDueTaskNote(HttpServletRequest req, HttpServletResponse resp) throws ParseException, IOException, EntityNotFoundException 
	{
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm",
				Locale.ENGLISH);
		Date due = formatter.parse(req.getParameter("due"));
		Long id_int = Long.parseLong(req.getParameter("id_int"));
		TaskLogic tLogic = new TaskLogic(req,resp);
		Task DueEdit = tLogic.EditDueTask(hotelId, id_int, due);
		resp.setContentType("text/plain; charset=UTF-8");
		if (DueEdit != null) {
			resp.getWriter().println(gson.toJson(DueEdit));
		} else {
			resp.getWriter().println(gson.toJson(false));
		}
	}
	private void EditDetailTaskNote(HttpServletRequest req, HttpServletResponse resp) throws ParseException, IOException, EntityNotFoundException 
	{
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String detail = req.getParameter("detail");
		Long id_int = Long.parseLong(req.getParameter("id_int"));
		TaskLogic tLogic = new TaskLogic(req,resp);
		Task DetailEdit = tLogic.EditDetailTask(hotelId, id_int, detail);
		resp.setContentType("text/plain; charset=UTF-8");
		if (DetailEdit != null) {
			resp.getWriter().println(gson.toJson(DetailEdit));
		} else {
			resp.getWriter().println(gson.toJson(false));
		}
	}
	private void editTrash(HttpServletRequest req, HttpServletResponse resp) throws ParseException, IOException, EntityNotFoundException 
	{
		Gson gson = new Gson();
		TaskLogic taskLogic = new TaskLogic(req,resp);
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		Long id_int = Long.parseLong(req.getParameter("id_int"));
		boolean trash = Boolean.parseBoolean(req.getParameter("trash"));
		Task t = taskLogic.GetTaskNote(id_int);
		t.setTrash(trash);
		t = taskLogic.UpdateTask(t);
		
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(t));
	}
	private void EditClose(HttpServletRequest req, HttpServletResponse resp) throws ParseException, IOException, EntityNotFoundException 
	{
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		TaskLogic taskLogic = new TaskLogic(req,resp);
		Long id_int = Long.parseLong(req.getParameter("id_int"));
		boolean complete = Boolean.parseBoolean(req.getParameter("complete"));
		Task t = taskLogic.GetTaskNote(id_int);
		t.setComplete(!complete);
		t = taskLogic.UpdateTask(t);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(t));
	}
	private void GetTaskNoteList(HttpServletRequest req, HttpServletResponse resp) throws IOException, ParseException
	{
		HttpSession session=req.getSession(true);
		long hotelId = 1;
		List<Task> tasklist = new ArrayList<Task>();
		if(session.getAttribute("hotelId") != null)
			hotelId = (Long)session.getAttribute("hotelId");
		String taskStringId = req.getParameter("task_id");
		String[] resArray = taskStringId.split(",");
		for(int i =0; i<resArray.length;i++)
		{
			Long task_id =Long.parseLong(resArray[i]);
			Task task = new TaskLogic(req,resp).GetTaskNote(hotelId,task_id);
			tasklist.add(task);
		}
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(tasklist));
	}
	private void GetFrontTask(HttpServletRequest req, HttpServletResponse resp) throws JSONException, IOException{
		
		HttpSession session=req.getSession(true);	
		long hotelId = 1;
		if(session.getAttribute("hotelId") != null)
			hotelId = (Long)session.getAttribute("hotelId");
		TaskLogic taskLogic = new TaskLogic(req,resp);
		GenericLogic gLogic = new GenericLogic(req,resp);
		
		List<Task> tasks = taskLogic.GetFist10Task(hotelId);
		Map<String,Long> count = new TaskLogic(req,resp).CountTask(hotelId);
		
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
		Date currentD = gLogic.ServerDateTime(hotelId);
		long minW;
		long minC;
		if(session.getAttribute("MinuteForWarning")!=null && session.getAttribute("MinuteForCritical")!=null){
			minW = (Long) session.getAttribute("MinuteForWarning");
			minC = (Long) session.getAttribute("MinuteForCritical");
		}else{
			General g = gLogic.GetGeneral(hotelId);
			minW = g.getMinuteForWarning();
			minC = g.getMinuteForCritical();
		}
		//s=status,r=roomName,i=isStar,t=tasktitle
		for(Task t:tasks){
			HashMap<String,Object> hash = new HashMap<String,Object>();
			hash.put("id", t.getId());
			if(t.isSetDue())
				if(!Util.addMins(t.getDue(),(minW*-1)).after(currentD) && currentD.before(Util.addMins(t.getDue(),(minC*-1)))) 
					hash.put("s", 'W');
				else if(currentD.after(Util.addMins(t.getDue(),(minC*-1))))
					hash.put("s", 'C');
				else hash.put("s", t.getStatus().charAt(0));
			else hash.put("s", t.getStatus().charAt(0));
			hash.put("r",t.getRoomName());
			hash.put("i", (t.isStar())? "t":"f");
			hash.put("t", t.getTaskTitle());
			list.add(hash);
		}
		
		HashMap<String,Object> result = new HashMap<String,Object>();
		result.put("Count",count);
		result.put("Task",list);
		
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(result));
	}
	private void GetFrontTaskAll(HttpServletRequest req, HttpServletResponse resp) throws JSONException, IOException{
		HttpSession session=req.getSession(true);
		long hotelId = 1;
		if(session.getAttribute("hotelId") != null)
			hotelId = (Long)session.getAttribute("hotelId");
		TaskLogic taskLogic = new TaskLogic(req,resp);
		GenericLogic gLogic = new GenericLogic(req,resp);
		
		List<Task> tasks = taskLogic.GetFistAllTask(hotelId);
		Map<String,Long> count = new TaskLogic(req,resp).CountTask(hotelId);
		
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
		Date currentD = gLogic.ServerDateTime(hotelId);
		long minW;
		long minC;
		if(session.getAttribute("MinuteForWarning")!=null && session.getAttribute("MinuteForCritical")!=null){
			minW = (Long) session.getAttribute("MinuteForWarning");
			minC = (Long) session.getAttribute("MinuteForCritical");
		}else{
			General g = gLogic.GetGeneral(hotelId);
			minW = g.getMinuteForWarning();
			minC = g.getMinuteForCritical();
		}
		//s=status,r=roomName,i=isStar,t=tasktitle
		for(Task t:tasks){
			HashMap<String,Object> hash = new HashMap<String,Object>();
			hash.put("id", t.getId());
			if(t.isSetDue())
				if(!Util.addMins(t.getDue(),(minW*-1)).after(currentD) && currentD.before(Util.addMins(t.getDue(),(minC*-1)))) 
					hash.put("s", 'W');
				else if(currentD.after(Util.addMins(t.getDue(),(minC*-1))))
					hash.put("s", 'C');
				else hash.put("s", t.getStatus().charAt(0));
			else hash.put("s", t.getStatus().charAt(0));
			hash.put("r",t.getRoomName());
			hash.put("i", (t.isStar())? "t":"f");
			hash.put("t", t.getTaskTitle());
			list.add(hash);
		}
		
		HashMap<String,Object> result = new HashMap<String,Object>();
		result.put("Count",count);
		result.put("Task",list);
		
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(result));
	}
	
	private void UpdateLastStay(HttpServletRequest req, HttpServletResponse resp) throws IOException, ParseException, EntityNotFoundException
	{
		HttpSession session=req.getSession(true);
		long hotelId = (Long)session.getAttribute("hotelId");
		long userId = (Long) session.getAttribute("userid");
		String currentCounter = (String) session.getAttribute("currentCounter");
		new LoginLogic(req,resp).UpdateLastStay(hotelId,userId);
		User obj =  new LoginLogic(req,resp).GetUserWithCache(userId);
		new LoginLogic(req,resp).SetCounter(hotelId,userId,currentCounter);
		String	sessionCheck = obj.getSessionid();
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(sessionCheck));
	}
}

